<script setup>
import { ref, reactive } from 'vue'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import UsernamePage from './components/UsernamePage.vue'
import ChatPage from './components/ChatPage.vue'

const colors = [
  '#2196F3', '#32c787', '#00BCD4', '#ff5652',
  '#ffc107', '#ff85af', '#FF9800', '#39bbb0'
]
const username = ref('')
const connecting = ref(false)
const messages = reactive([])
let stompClient = null

const getAvatarColor = (messageSender) => {
  let hash = 0
  for (let i = 0; i < messageSender.length; i++) {
    hash = 31 * hash + messageSender.charCodeAt(i)
  }
  return colors[Math.abs(hash % colors.length)]
}

const fetchHistory = async () => {
  try {
    const response = await fetch('/api/chat/history')
    const historyData = await response.json()

    historyData.forEach(msg => {
      messages.push({
        sender: msg.sender,
        content: msg.content,
        timestamp: msg.timestamp,
        type: msg.type,
        color: getAvatarColor(msg.sender)
      })
    })
  } catch (error) {
    console.error('Error fetching chat history:', error)
  }
}

const connect = (name) => {
  username.value = name.trim()
  if (!username.value) return
  connecting.value = true

  const socket = new SockJS('/ws')
  stompClient = Stomp.over(socket)
  stompClient.connect({},
      () => {
        connecting.value = false

        // 获取历史消息
        fetchHistory().then(() => {
          // 订阅和发送用户加入信息
          stompClient.subscribe('/topic/public', onMessageReceived)
          stompClient.send(
              '/app/chat.addUser',
              {},
              JSON.stringify({ sender: username.value, type: 'JOIN' })
          )
        })
      },
      (error) => {
        connecting.value = false
        console.error('Connection error:', error)
      }
  )
}

const sendMessage = (messageContent, messageType) => {
  try {
    if (messageContent && stompClient) {
      const chatMessage = {
        sender: username.value,
        content: messageContent,
        type: messageType
      };
      stompClient.send('/app/chat.sendMessage', {}, JSON.stringify(chatMessage));
    }
  } catch (error) {
    console.error('Message send error:', error);
  }
}

const onMessageReceived = (payload) => {
  const message = JSON.parse(payload.body)
  messages.push({
    ...message,
    color: ['CHAT', 'IMAGE'].includes(message.type)
        ? getAvatarColor(message.sender)
        : 'transparent'
  })
}
</script>

<template>
  <div id="poster">
    <UsernamePage v-if="!username" @submit-username="connect" />
    <ChatPage v-else :messages="messages" :connecting="connecting" @send-message="sendMessage"/>
  </div>
</template>

<style scoped>
#poster {
  background: url("./assets/eva.jpeg") no-repeat center;
  background-size: cover;
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
}
</style>